package uk.ac.lkl.lpp.ui;



import java.awt.Color;
import java.awt.GridLayout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import javax.swing.JTextField;

import uk.ac.lkl.lpp.model.PedagogyPlanModel;

import uk.ac.lkl.lpp.model.ldo.TeachingMethod;


/**
 * A view of a teaching method that uses a text field to edit some attribute of
 * it.
 * 
 * @author Darren Pearce
 * @version $Revision$
 * @version $Date$
 * 
 */
public abstract class TextFieldTeachingMethodView extends TeachingMethodView {

    private JTextField textField;


    public TextFieldTeachingMethodView(TeachingMethod teachingMethod,
            PedagogyPlanModel pedagogyPlanModel) {
        super(teachingMethod, pedagogyPlanModel);
        setLayout(new GridLayout(1, 1));
        textField = new JTextField();
        add(textField);
        updateView();
        addListeners();
    }


    public String getValue() {
        return textField.getText();
    }


    protected void setValue(String value) {
        textField.setText(value);
    }


    private void setValid(boolean valid) {
        if (valid)
            textField.setForeground(Color.BLACK);
        else
            textField.setForeground(Color.RED);
    }


    public void processValue() {
        boolean ok = doProcessValue();
        setValid(ok);
    }


    protected abstract boolean doProcessValue();


    private void addListeners() {
        addFocusListener();
        addActionListener();
    }


    private void addFocusListener() {
        textField.addFocusListener(new FocusAdapter() {

            public void focusLost(FocusEvent e) {
                processValue();
            }
        });
    }


    private void addActionListener() {
        textField.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                processValue();
            }
        });
    }

}
